import time
import requests

try:
    import pika
except ImportError:
    pika = None

from logger import log


def fetch_xml(url: str, timeout: int = 15) -> str:
    resp = requests.get(url, timeout=timeout)
    resp.raise_for_status()
    return resp.text


def publish_to_rabbitmq(body: str, host: str, port: int, username: str, password: str, queue: str) -> None:
    if pika is None:
        raise RuntimeError("pika not installed")
    credentials = pika.PlainCredentials(username, password) if username and password else None
    params = pika.ConnectionParameters(host=host, port=port, credentials=credentials)
    connection = pika.BlockingConnection(params)
    channel = connection.channel()
    channel.queue_declare(queue=queue, durable=True)
    channel.basic_publish(
        exchange="",
        routing_key=queue,
        body=body.encode("utf-8"),
        properties=pika.BasicProperties(delivery_mode=2, content_type="application/xml"),
    )
    connection.close()


def main() -> None:
    url = "https://platform.nezhwl.com/api/zkr/tos_xml"
    # host = "rabbitmq-cn-w5g4jenxu01.cn-beijing.amqp-21.net.mq.amqp.aliyuncs.com"
    host = "localhost"
    port = 5672
    # username = "MjpyYWJiaXRtcS1jbi13NWc0amVueHUwMTpMVEFJV3hRM3ZEeGdVQlVO"
    username = "guest"
    # password = "MzU5RTc5OEUyMTdDQTE2QjJBQzZBQTNENzMwRkFGN0JDNDg3RjU3NToxNzYzOTY5NTAzNDMz"
    password = "guest"
    queue = "WAREHOUSE_PARK_DATA"

    while True:
        try:
            xml_text = fetch_xml(url)
            if not xml_text.strip():
                log.info("empty xml, skip publish")
            else:
                publish_to_rabbitmq(xml_text, host, port, username, password, queue)
                log.info(f"rabbitmq published queue={queue} len={len(xml_text)}")
        except Exception as e:
            log.error(f"rabbitmq publish failed: {e}")
        time.sleep(5)

def test_publish_to_rabbitmq() -> None:
    body = "<test>123</test>"
    host = "rabbitmq-cn-w5g4jenxu01.cn-beijing.amqp-21.net.mq.amqp.aliyuncs.com"
    port = 5672
    username = "MjpyYWJiaXRtcS1jbi13NWc0amVueHUwMTpMVEFJV3hRM3ZEeGdVQlVO"
    password = "MzU5RTc5OEUyMTdDQTE2QjJBQzZBQTNENzMwRkFGN0JDNDg3RjU3NToxNzYzOTY5NTAzNDMz"
    queue = "WAREHOUSE_PARK_DATA"
    publish_to_rabbitmq(body, host, port, username, password, queue)


def test_subscribe_from_rabbitmq() -> None:
    host = "rabbitmq-cn-w5g4jenxu01.cn-beijing.amqp-21.net.mq.amqp.aliyuncs.com"
    port = 5672
    username = "MjpyYWJiaXRtcS1jbi13NWc0amVueHUwMTpMVEFJV3hRM3ZEeGdVQlVO"
    password = "MzU5RTc5OEUyMTdDQTE2QjJBQzZBQTNENzMwRkFGN0JDNDg3RjU3NToxNzYzOTY5NTAzNDMz"
    queue = "WAREHOUSE_PARK_DATA"

    if pika is None:
        raise RuntimeError("pika not installed")

    credentials = pika.PlainCredentials(username, password) if username and password else None
    params = pika.ConnectionParameters(host=host, port=port, credentials=credentials)
    connection = pika.BlockingConnection(params)
    channel = connection.channel()
    channel.queue_declare(queue=queue, durable=True)

    def callback(ch, method, properties, body):
        log.info(f"rabbitmq received message: {body.decode('utf-8')}")

    channel.basic_consume(queue=queue, on_message_callback=callback, auto_ack=True)

    log.info("rabbitmq waiting for messages. To exit press CTRL+C")
    channel.start_consuming()


if __name__ == "__main__":
    # test_subscribe_from_rabbitmq()
    # while True:
    #     test_publish_to_rabbitmq()
    #     log.info("test_publish_to_rabbitmq done")
    #     time.sleep(5)
    main()